package com.sxt.service.impl;

import com.sxt.entity.Sku;
import com.sxt.mapper.SkuMapper;
import com.sxt.model.ShopCartItem;
import com.sxt.service.SkuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.List;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * 单品SKU表 服务实现类
 * </p>
 *
 * @author liangtiandong
 * @since 2019-12-17
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

	@Autowired
	private SkuMapper skuMapper ;

	/**
	 * 执行sku的库存--
	 */
	@Override
	public void decrStock(List<ShopCartItem> cartItems) {
		if(cartItems==null || cartItems.isEmpty()) {
			return ;
		}
		for (ShopCartItem shopCartItem : cartItems) {
			Long skuId = shopCartItem.getSkuId();
			Integer prodCount = shopCartItem.getProdCount();
			Sku sku = skuMapper.selectOne(new LambdaQueryWrapper<Sku>()
					.select(Sku::getStocks)
					.eq(Sku::getSkuId, skuId));
			int remainCount = 0 ;
			if((remainCount=(sku.getStocks()-prodCount))<0) {
				throw new RuntimeException("库存不足");
			}
			sku.setSkuId(skuId) ;
			sku.setStocks(remainCount) ;
			sku.setUpdateTime(LocalDateTime.now()) ;
			skuMapper.updateById(sku) ;
		}
	}

}
